/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    Animated,
    Platform,
    TouchableWithoutFeedback,
    InteractionManager,
    Alert
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import GoodsItem from '../components/GoodsItem';
import BaiduMap from './BaiduMap';
import SelectCity from '../components/SelectCity';
import ImageCropPicker from 'react-native-image-crop-picker';
import shopService from '../lib/services/shopService';
import StorageUser from '../lib/plugins/StorageUser';
import LoadingModal from '../components/LoadingModal';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class EditStore extends Component{
    constructor(props) {
        super(props);
        var $this = this;
        this.token = '';
        this.state = {
            showStaturs:'',
            modalVisible:false,
            statursList:['个体商户','企业商户'],
            areaList:['狗粮','猫粮','其他'],
            statursName:'未选择',//商户类型
            cityText:'未选择',//所在城市
            location:'未选择',//位置
            shopAddress:'xx区xx路xx号',//详细地址
            shopName:'商户或店铺名称',//店铺名称
            shopArea:'未选择',//经营范围
            userName:'填写联系人',//企业联系人
            mobile:'填写联系电话',//联系电话
            IDNumber:'填写身份证号码',//身份证号
            businessMobile:'填写客服电话',//客服电话
            userId:'',//用户ID
            id:this.props.navigation.state.params.id,
            outdoorList:[],//店铺门脸图列表
            outdoorDataList:[],
            outdoorText:'',
            environmentList:[],//店铺环境图列表
            environmentDataList:[],
            environmentText:'',
            licenseList:[],//营业执照图列表
            licenseDataList:[],
            licenseText:'',
            IDList:[],//身份证图列表
            IDDataList:[],
            IDText:'',
            shopInfo:'',//店铺介绍
            licenseNum:'填写营业执照号码',//营业执照号码
            mapId:'',//地图店铺ID
            shopData:{},
            load:false
        };
        
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                InteractionManager.runAfterInteractions(() => {
                    $this.getEditData();
                });               
            }).catch(err=> {
                console.log(err)
            });
    }
    // 模态框
    renderNameModal(){
        var list = [];
        if(this.state.showStaturs=='商户类型'){
            list = this.state.statursList;
        }else if(this.state.showStaturs=='经营范围'){
            list = this.state.areaList;
        }
        return(
            <Modal
                transparent={true}
                visible={this.state.modalVisible}
                onRequestClose={()=>this.requestClose()}>
                <TouchableWithoutFeedback onPress={()=>this.setState({modalVisible:false})}>
                    <View style={styles.modalBox}>
                        <View style={styles.listBorder}>
                            {this.renderModalList(list)}
                        </View>
                    </View>
                </TouchableWithoutFeedback>
            </Modal>
        )
    }
    // 渲染模态框内的列表
    renderModalList(list){
        return(
            list.map((item,i)=>{
                return(
                    <TouchableOpacity key={i} onPress={()=>this.changeName(item)}>
                        <View style={styles.listItem}>
                            <Text>{item}</Text>
                        </View>
                    </TouchableOpacity>
                )
            })
            
        )
    }
    render(){
        return (
            <View style={styles.container}>
                {this.renderNameModal()}
                <NavigationBar 
                    leftPress={()=>this.goBack()}
                    leftIcon={'left'} 
                    titleText={'编辑店铺'}/>
                <LoadingModal visible={this.state.load} onRequestClose={()=>{console.log('666')}}/>
                <ScrollView>
                    <View style={{height:30,paddingLeft:10,justifyContent:'center'}}>
                        <Text style={{color:'#FF0101'}}>*必填项</Text>
                    </View>
                    <View style={styles.itemBox}>
                        <TouchableOpacity onPress={()=>this._goSelectCity()}>
                            <GoodsItem style={styles.itemBorder} title={'所在城市'} name={this.state.cityText}/>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={()=>this.goBaiduMap()}>
                            <GoodsItem style={styles.itemBorder} title={'位置'} name={this.state.location.address}/>
                        </TouchableOpacity>
                        
                        <GoodsItem onChangeText={(text)=>this.getShopAddress(text)} title={'详细地址'} hasInput={true} onBlur={()=>this.blurFun(0)} defaultValue={this.state.shopAddress}/>
                    </View>
                    <View style={[styles.itemBox,{marginTop:20}]}>
                        <GoodsItem onChangeText={(text)=>this.getShopName(text)} style={styles.itemBorder} title={'商户名称'} hasInput={true} onBlur={()=>this.blurFun(1)} defaultValue={this.state.shopName}/>
                        <TouchableOpacity onPress={()=>this.choseStaturs('商户类型')}>
                            <GoodsItem style={styles.itemBorder} title={'商户类型'} name={this.state.statursName}/>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={()=>this.choseStaturs('经营范围')}>
                            <GoodsItem style={styles.itemBorder} title={'经营范围'} name={this.state.shopArea}/>
                        </TouchableOpacity>
                        <GoodsItem onChangeText={(text)=>this.getUserName(text)} style={styles.itemBorder} title={'企业联系人'} hasInput={true} onBlur={()=>this.blurFun(2)} defaultValue={this.state.userName}/>
                        <GoodsItem onChangeText={(text)=>this.getMobile(text)} style={styles.itemBorder} title={'联系电话'} hasInput={true} onBlur={()=>this.blurFun(3)} defaultValue={this.state.mobile}/>
                        <GoodsItem onChangeText={(text)=>this.getIDNumber(text)} style={styles.itemBorder} onBlur={()=>this.blurFun(5)} title={'身份证号码'} hasInput={true} defaultValue={this.state.IDNumber}/>
                        <GoodsItem onChangeText={(text)=>this.getBusinessMobile(text)} style={styles.itemBorder} title={'客服电话'} hasInput={true} onBlur={()=>this.blurFun(4)} defaultValue={this.state.businessMobile}/>
                        <GoodsItem onChangeText={(text)=>this.getLicenseNum(text)} style={styles.itemBorder} title={'营业执照号'} hasInput={true} onBlur={()=>this.blurFun(6)} defaultValue={this.state.licenseNum}/>
                        <ImageItem that={this} style={styles.itemBorder} title={'店铺门脸图'} data={this.state.outdoorList} onPress={()=>this.choseImg('outdoorList')} staturs={'outdoorList'}/>
                        <ImageItem that={this} data={this.state.environmentList} onPress={()=>this.choseImg('environmentList')} style={styles.itemBorder} staturs={'environmentList'} title={'店内环境图(最多添加9张)'}/>
                        <View>
                            <View style={{flexDirection:'row',height:30,alignItems:'center'}}>
                                <Text style={{color:'#FF1717'}}>*</Text>
                                <Text>店面介绍</Text>
                            </View>
                            <View>
                                <TextInput
                                    style={{padding:3}}
                                    underlineColorAndroid={'transparent'}
                                    textAlignVertical={'top'}
                                    multiline={true}
                                    numberOfLines={7}
                                    onChangeText={(text)=>this.getShopInfo(text)}
                                    defaultValue={this.state.shopInfo}
                                    onBlur={()=>this.blurFun(7)}/>
                            </View>
                        </View>
                    </View>
                    <View style={[styles.itemBox,{marginTop:20}]}>
                        <ImageItem that={this} data={this.state.licenseList} onPress={()=>this.choseImg('licenseList')} style={styles.itemBorder} title={'营业执照'} staturs={'licenseList'}/>
                        <ImageItem that={this} data={this.state.IDList} onPress={()=>this.choseImg('IDList')} staturs={'IDList'} text={'正面'} style={styles.itemBorder} title={'身份证照片'}/>
                    </View>
                    <View style={{marginBottom:20}}>
                        <View style={{height:40,justifyContent:'center',alignItems:'center'}}>
                            <Text style={styles.textColor}>注 : 为了便于审核,以上信息需要您如实填写</Text>
                        </View>
                        <View style={{alignItems:'center'}}>
                            <TouchableOpacity onPress={()=>this.editShopData()} style={{width:3*width/4}}>
                                <View style={{height:40,justifyContent:'center',width:3*width/4,alignItems:'center',backgroundColor:'rgb(79,145,237)',borderRadius:3}}>
                                    <Text style={{color:'#fff'}}>完成</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                    
                </ScrollView>
            </View>
        )

    }
    getEditData(){
        var $this = this;
        shopService.shopIdFind(function(data){
            alert(JSON.stringify(data))
            if(data.code==10000){
                var obj = data.data;
                // alert(JSON.stringify(obj));
                // statursName:'未选择',//商户类型
                // cityText:'未选择',//所在城市
                // location:'未选择',//位置
                // shopAddress:'',//详细地址
                // shopName:'商户或店铺名称',//店铺名称
                // shopArea:'',//经营范围
                // userName:'',//企业联系人
                // mobile:'',//联系电话
                // IDNumber:'',//身份证号
                // businessMobile:'',//客服电话
                // userId:'',//用户ID
                // outdoorList:[],//店铺门脸图列表
                // environmentList:[],//店铺环境图列表
                // licenseList:[],//营业执照图列表
                // IDList:[],//身份证图列表
                // shopInfo:'',//店铺介绍
                // licenseNum:'',//营业执照号码
                // mapId:'',//地图店铺ID
                var list = obj.shop_image_one.split(',');
                var arr = [];
                var imgDataArr = [];
                var len = list.length;
                for(var i=0;i<len;i++){
                    if(list[i]!=''){
                        var object = {};
                        object.path = 'http://peita.oss-cn-beijing.aliyuncs.com/' + list[i];
                        arr.push(object);
                        imgDataArr.push(object);
                    }
                    
                }
                var positionObj = {};
                positionObj.address = obj.position;
                positionObj.lat = obj.lat;
                positionObj.lng = obj.lng;
                $this.setState({
                    shopData:obj,
                    cityText:obj.in_city,
                    location:positionObj,
                    shopAddress:obj.detailed_address,
                    statursName:obj.merchant_type,
                    shopName:obj.merchant_name,
                    shopArea:obj.scope,
                    userName:obj.shopkeeper,
                    mobile:obj.phone,
                    businessMobile:obj.tel,
                    userId:obj.user_id,
                    IDNumber:obj.id_card,
                    licenseNum:obj.business_num,
                    mapId:obj.uid,
                    shopInfo:obj.shop_introduce,
                    outdoorList:[{path:obj.front}],
                    environmentList:arr,
                    environmentDataList:imgDataArr,
                    licenseList:[{path:obj.license_one}],
                    IDList:[{path:obj.id_card_img}],
                })
            }
        },$this.state.id,$this.token)
    }
    
    // 返回按钮点击事件
    goBack(){
        this.props.navigation.goBack();
    }
    // 选择图片
    choseImg(name){
        var $this = this;
        if(name=='outdoorList' && this.state.outdoorList.length==1){
            return;
        }else if(name=='environmentList' &&this.state.environmentList.length>=9){
            return;
        }else if(name=='licenseList' && this.state.licenseList.length==1){
            return;
        }else if(name=='IDList' && this.state.IDList.length==1){
            return;
        }
        var obj = {};
        obj.s_id = $this.state.id;
        var imgArr = [];
        if(name=='environmentList'){
            ImageCropPicker.openPicker({
                    multiple: true,
                    maxFiles:9,
                    mediaType:'photo',
                }).then(images => {
                    
                    var len = images.length;
                    var arr = [];
                    for(var i=0;i<len;i++){
                        var source = {};
                        if (Platform.OS === 'android') {
                            source = {path: images[i].path, isStatic: true};
                            arr.push(source);
                        } else {
                            source = {path: images[i].path.replace('file://', ''), isStatic: true};
                            arr.push(source);
                        }
                    }
                    var list = $this.state.environmentList;
                    var arrList = $this.state.environmentDataList;
                    list = list.concat(arr);
                    arrList = arrList.concat(images);
                    if(list.length>9){
                        list.splice(9);
                        arrList.splice(9);
                    }
                    $this.setState({
                        environmentList : list,
                        environmentDataList : arrList,
                    });
                }).catch((err)=>{
                    console.log(err)
                })
        }else{
            ImageCropPicker.openPicker({
                    width: 300, 
                    height: 300, 
                    cropping: true,
                    mediaType:'photo',
                }).then(image => { 
                    var source;
                    if (Platform.OS === 'android') {
                        source = {path: image.path, isStatic: true};
                    } else {
                        source = {path: image.path.replace('file://', ''), isStatic: true};
                    }
                    if(name=='outdoorList'){
                        var list = $this.state.outdoorList;
                        var arr = $this.state.outdoorDataList;
                        list.push(source);
                        arr.push(image);
                        $this.setState({
                            outdoorList : list,
                            outdoorDataList : arr
                        });
                        obj.type = 13;
                        imgArr['front'] = image.path;
                        shopService.shopIdSave(function(result){
                            alert(JSON.stringify(result))
                            if(result.code==10000){
                                console.log('成功！');
                            }
                        },obj,imgArr,$this.token)
                    }else if(name=='licenseList'){
                        var list = $this.state.licenseList;
                        var arr = $this.state.licenseDataList;
                        list.push(source);
                        arr.push(image);
                        $this.setState({
                            licenseList : list,
                            licenseDataList : arr,
                        });
                        obj.type = 18;
                        imgArr['license_one'] = image.path;
                        shopService.shopIdSave(function(result){
                            alert(JSON.stringify(result))
                            if(result.code==10000){
                                console.log('成功！');
                            }
                        },obj,imgArr,$this.token)
                    }else if(name=='IDList'){
                        var list = $this.state.IDList;
                        var arr = $this.state.IDDataList;
                        list.push(source);
                        arr.push(image);
                        $this.setState({
                            IDList : list,
                            IDDataList : arr,
                        });
                        obj.type = 19;
                        imgArr['id_card_img'] = image.path;
                        shopService.shopIdSave(function(result){
                            alert(JSON.stringify(result))
                            if(result.code==10000){
                                console.log('成功！');
                            }
                        },obj,imgArr,$this.token)
                    }
                }).catch((err)=>{
                    console.log(err)
                })
        }                  
    }
    // 跳转到百度地图
    goBaiduMap(){
        var $this = this;
        const {navigate } = this.props.navigation;
        navigate('BaiduMap',{getLocation:(data)=>{
            $this.setState({
                location:data
            })
            if($this.state.shopData.position!=data.address){
                var obj = {};
                obj.s_id = $this.state.id;
                obj.type = 2;
                obj.position = data.address;
                shopService.shopIdSave(function(result){
                    if(result.code==10000){
                        console.log('成功！');
                    }
                },obj,[],$this.token)
            }
        }})
    }
    // 跳转到选择城市页面
    _goSelectCity() {
        var $this = this;
        const {navigate } = this.props.navigation;
        navigate('SelectCity',{getAddress:(data)=>{
            var text = data.province+data.city+data.area
            $this.setState({
                cityText:text
            })
            if($this.state.shopData.cityText!=text){
                var obj = {};
                obj.s_id = $this.state.id;
                obj.type = 1;
                obj.in_city = text;
                shopService.shopIdSave(function(result){
                    if(result.code==10000){
                        console.log('成功！')
                    }
                },obj,[],$this.token)
            }
        }})
    }
    blurFun(index){
        var $this = this;
        var stateArr = ['shopAddress','shopName','userName','mobile','businessMobile','IDNumber','licenseNum','shopInfo'];
        var arr = [3,4,7,8,9,10,11,12];
        var dataArr = ['detailed_address','merchant_name','shopkeeper','phone','tel','id_card','business_num','shop_introduce'];
        if(this.state.shopData[dataArr[index]]!=this.state[stateArr[index]]){
            var obj = {};
            obj.s_id = this.state.id;
            obj.type = arr[index];
            obj[dataArr[index]] = this.state[stateArr[index]];
            shopService.shopIdSave(function(result){
                // alert(JSON.stringify(result))
                if(result.code==10000){
                    console.log('成功！'); 
                }
            },obj,[],$this.token)
        }

    }
    // 模态框列表点击事件
    changeName(name){
        var $this = this;
        if(this.state.showStaturs=='商户类型'){
            if(name!=this.state.shopData.merchant_type){
                var obj = {};
                obj.s_id = this.state.id;
                obj.type = 5;
                obj.merchant_type = name;
                shopService.shopIdSave(function(result){
                    if(result.code==10000){
                        console.log('成功！');
                    }
                },obj,[],$this.token)
            }
            this.setState({
                statursName:name,
                modalVisible:false
            })
        }else if(this.state.showStaturs=='经营范围'){
            if(name!=this.state.shopData.scope){
                var obj = {};
                obj.s_id = this.state.id;
                obj.type = 6;
                obj.scope = name;
                shopService.shopIdSave(function(result){
                    if(result.code==10000){
                        console.log('成功！');
                    }
                },obj,[],$this.token)
            }
            this.setState({
                shopArea:name,
                modalVisible:false
            })
        }
        
    }
    // 显示模态框
    choseStaturs(staturs){
        this.setState({
            showStaturs:staturs,
            modalVisible:true
        })
    }
    getShopAddress(text){
        this.setState({
            shopAddress:text
        })
    }
    getShopName(text){
        this.setState({
            shopName:text
        })
    }
    getUserName(text){
        this.setState({
            userName:text
        })
    }
    getMobile(text){
        this.setState({
            mobile:text
        })
    }
    getIDNumber(text){
        this.setState({
            IDNumber:text
        })
    }
    getBusinessMobile(text){
        this.setState({
            businessMobile:text
        })
    }
    getShopInfo(text){
        this.setState({
            shopInfo:text
        })
    }
    getLicenseNum(text){
        this.setState({
            licenseNum:text
        })
    }
    editShopData(){
        var $this  = this;
        var arr = [];
        var list = this.state.environmentDataList;
        var len = list.length;
        var imgText = '';
        var index = 1;
        for(var i=0;i<len;i++){
            if(/http:\/\/peita.oss-cn-beijing.aliyuncs.com\//.test(list[i].path)){
                imgText+=list[i].path.replace(/http:\/\/peita.oss-cn-beijing.aliyuncs.com\//g,'')+',';
            }else{
                arr['img'+index] = list[i].path;
                index++;
            }
        }
        this.setState({
            load:true
        })
        if(arr['img1']){
            shopService.upFile(function(data){
                // alert(JSON.stringify(data));
                if(data.code==10000){
                    var obj = {};
                    obj.s_id = $this.state.id;
                    obj.type = 14;
                    obj.shop_image_one = (imgText==''?data.data:(imgText+','+data.data));
                    shopService.shopIdSave(function(result){ 
                        if(result.code==10000){
                            $this.setState({
                                load:false
                            })
                            Alert.alert('提示信息',
                                        '修改成功',
                                        [{text: '确定', onPress: () => {
                                            $this.props.navigation.state.params.upData();
                                            $this.goBack();
                                        }}])
                        }
                    },obj,[],$this.token);
                }
            },arr,$this.token)
        }else{
            if(imgText==''){
                alert('请添加图片！');
            }else{
                var obj = {};
                obj.s_id = $this.state.id;
                obj.type = 14;
                obj.shop_image_one = imgText;
                shopService.shopIdSave(function(result){
                    // alert(JSON.stringify(result));
                    $this.setState({
                        load:false
                    })
                    if(result.code==10000){
                            Alert.alert('提示信息',
                                        '修改成功',
                                        [{text: '确定', onPress: () => $this.goBack()}])
                    }
                },obj,[],$this.token);
            }
            
        }
        
    }
}

class ImageItem extends Component{
    showImages(){
        var list = this.props.data;
        if(list && list.length>0){
            return(
                list.map((item,i)=>{
                    if(i<9){
                        return(
                            <View key={i} style={{paddingRight:10}}>
                                <TouchableOpacity style={{paddingTop:10,paddingRight:10}} onPress={()=>this.selectItem(i)}>
                                    <ImageWrapper style={{width:20,height:20,position:'absolute',top:0,right:0,zIndex:1000}} icon={'stop'}/>
                                    <Image style={{width:60,height:60}} source={{uri:item.path}}/>               
                                </TouchableOpacity>
                            </View>
                        )
                    }
                    
                })
            )
        }else{
            return; 
        }
        
    }

    selectItem(key){
        var that = this.props.that;
        var staturs = this.props.staturs;
        
        // alert(JSON.stringify(that.state.outdoorList))
        if(staturs=='outdoorList'){
            var list = [];
            list = that.state.outdoorList;
            list.splice(key,1);
            that.setState({
                outdoorList:list
            })
        }else if(staturs=='environmentList'){
            var list = [];
            list = that.state.environmentList;
            arr = that.state.environmentDataList;
            list.splice(key,1);
            arr.splice(key,1);
            that.setState({
                environmentList:list,
                environmentDataList:arr,
            })
        }else if(staturs=='licenseList'){
            var list = [];
            list = that.state.licenseList;
            list.splice(key,1);
            that.setState({
                licenseList:list
            })
        }else if(staturs=='IDList'){
            var list = [];
            list = that.state.IDList;
            list.splice(key,1);
            that.setState({
                IDList:list
            })
        }
        
    }

    render(){
        return(
            <View style={this.props.style}>
                <View style={{flexDirection:'row',height:30,alignItems:'center'}}>
                    <Text style={styles.textColor}>*{this.props.text}</Text>
                    <Text>{this.props.title}</Text>
                </View>
                <View style={{width:width,padding:10,flexDirection:'row',flexWrap:'wrap'}}>
                    {this.showImages()}
                    <TouchableOpacity onPress={this.props.onPress}>
                        <ImageWrapper style={{marginTop:10}} width={60} height={60} icon={'addImg'}/>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },

        }),
    }, 
    itemBorder:{
        borderBottomWidth:1,
        borderBottomColor:'#DFDFE2'
    },
    itemBox:{
        borderBottomWidth:1,
        borderBottomColor:'#DFDFE2',
        borderTopWidth:1,
        borderTopColor:'#DFDFE2',
        paddingLeft:10,
        backgroundColor:'#fff'
    },
    textColor:{
        color:'#FF1717'
    },
    modalBox:{
        flex:1,
        backgroundColor:'rgba(3,3,3,.2)',
        justifyContent:'center',
        alignItems:'center',
    },
    listItem:{
        width:3*width/4,
        height:40,
        justifyContent:'center',
        backgroundColor:'#fff',
        paddingLeft:10,
    },
    
});